﻿using System.Collections.Generic;

namespace SGEngine.ProfilerEx
{
    /// <summary>
    /// 通知类
    /// TODO: 支持延迟触发（合并）事件
    /// </summary>
    public class Notifier
    {
        private Dictionary<string, StandardDelegate> m_eventMap = new Dictionary<string, StandardDelegate>();
        public delegate void StandardDelegate(params object[] arg1);
        /// <summary>
        /// 添加某事件处理
        /// </summary>
        /// <param name="eventName">事件名称</param>
        /// <param name="pFun">事件回调</param>
        public void AddEventHandler(string eventName, StandardDelegate pFun)
        {
            var key = eventName;
            if (!m_eventMap.ContainsKey(key))
            {
                m_eventMap[key] = pFun;
            }
            else
            {
                m_eventMap[key] += pFun;
            }
        }
        
        
        /// <summary>
        /// 移除指定事件处理函数
        /// </summary>
        /// <param name="eventName">事件名称</param>
        /// <param name="pFun">事件回调</param>
        public void RemoveEventHandler(string eventName, StandardDelegate pFun)
        {
            if (m_eventMap.ContainsKey(eventName))
            {
                m_eventMap[eventName] -= pFun;
            }
        }
        /// <summary>
        /// 触发某事件，将通知到所有的事件监听对象
        /// </summary>
        /// <param name="eventName">事件名称</param>
        /// <param name="e">事件参数</param>
        virtual public void RaiseEvent(string eventName, params object[] e)
        {
            var key = eventName;
            StandardDelegate fun = null;
            if (m_eventMap.TryGetValue(key, out fun))
            {
                fun?.Invoke(e);
            }
        }
        /// <summary>
        /// 判断某事件是否已经注册，可用于防止模型重命名
        /// </summary>
        /// <param name="eventName">事件名称</param>
        /// <returns>是否已经存在</returns>
        public bool HasEvent(string eventName)
        {
            var key = eventName;
            return m_eventMap.ContainsKey(key);
        }
        /// <summary>
        /// 移除某事件的所有委托
        /// </summary>
        /// <param name="eventName">事件名称</param>
        public void RemoveAllEventHandler(string eventName)
        {
            var key = eventName;
            if (m_eventMap.ContainsKey(key))
            {
                m_eventMap.Remove(key);
            }
        }
        /// <summary>
        /// 清空所有注册
        /// </summary>
        public void ClearEventHandle()
        {
            m_eventMap.Clear();
        }
    }
}